package net.atomarrow.pr.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import net.atomarrow.annotation.Inject;
import net.atomarrow.db.parser.Conditions;
import net.atomarrow.mapping.ActionMapping;
import net.atomarrow.pr.domain.TbRoleFunc;
import net.atomarrow.services.Service;
import net.atomarrow.util.RegexUtil;

public class RoleFuncService extends Service {
    @Inject
    private ActionMapping actionMapping;

	public Set<String> getRoleFuncSet(int roleId){
		List<TbRoleFunc> roleFuncs = getByRoleId(roleId);
		Set<String> set = new HashSet<String>();
		String url;
		List<String> paths = actionMapping.getAllMappingPath();
		for(TbRoleFunc roleFunc:roleFuncs){
		    url=roleFunc.getFuncUrl();
		    String regex = "\\*|\\^|\\$|\\+|\\-|\\[|\\{";
		    if(RegexUtil.match(regex, url)){
		        set.addAll(parseMappingPath(paths,url));
		    }else{
		        set.add(roleFunc.getFuncUrl());
		    }
		}
		return set;
	}
	
	private List<String> parseMappingPath(List<String> paths, String url) {
	    List<String> mappingPaths= new ArrayList<String>();
	    for(String path:paths){
	        if(mapping(path,url)){
	            mappingPaths.add(path);
	        }
	    }
        return mappingPaths;
    }

    private boolean mapping(String path, String url) {
        //for example: /account/index  to mapping  /account/*
        return RegexUtil.match(url, path);
    }

    public List<TbRoleFunc> getByRoleId(int roleId){
		Conditions conditions = new Conditions(TbRoleFunc.class);
		conditions.putEW("roleId", roleId);
		return getList(conditions);
	}
}
